package com.ocean.dynamic;

/**
 * <Description> <br>
 *
 * @author linmiaolai@sanyygp.com<br>
 * @version 1.0<br>
 * @date 2023/03/31 <br>
 */
public class Dp01 {
    public static void main(String[] args) {
        int[] weight = {1, 3, 4};
        int[] value = {15, 20, 30};
        int bagSize = 4;
        Dp01 dp01 = new Dp01();
        dp01.testWeightBagProblem(weight, value, bagSize);
    }

    private void testWeightBagProblem(int[] weight, int[] value, int bagSize) {
        int n = weight.length;
        int[][] dp = new int[n][bagSize + 1];
        // 初始化
        // 背包大小为0是，价值为0
        for (int i = 0; i < n; i++) {
            dp[i][0] = 0;
        }
        // 当只有一个物品时，只有背包的大小比物品的重量大时 才有价值，否则默认是0
        for (int j = weight[0]; j <= bagSize; j++) {
            dp[0][j] = value[0];
        }
        // 遍历物品
        for (int i = 1; i < n; i++) {
            // 遍历背包大小
            for (int j = 1; j <= bagSize; j++) {
                // 判断当前物品是佛可以放到背包中
                if (weight[i] > j) {
                    // 放不下
                    dp[i][j] = dp[i - 1][j];
                } else {
                    // 可以放：判断放与不放的最大值
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
                }
            }
        }

        // 打印dp数组
        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= bagSize; j++) {
                System.out.print(dp[i][j] + "\t");
            }
            System.out.println("\n");
        }
    }
}
